<template>
  <view class="container" v-if="detail">
    <view class="header">
      <view class="order-status">
        <block v-if="detail.groupEndTime > nowDate">
          <view class="_title">待成团</view>
        </block>
        <block v-else>
          <view class="_title">已结束</view>
        </block>
      </view>
      <view class="_bg"></view>
    </view>
    <!--  拼团  -->
    <view class="card">
      <view class="goods-detail">
        <x-order-goods v-if="orderGoods" :detail="orderGoods" />
      </view>
      <view class="collage">
        <view class="countdown" v-if="detail.groupEndTime > nowDate">
          <x-countdown :end="detail.groupEndTime" auto @change="handleCountdownChange">
            <template v-if="countdownData">
              <view class="_time">
                <text class="_tips">已有{{ detail.orderGroupList.length }}人跟团，组团剩余时间：</text>
                <view class="_clock">{{ countdownData.minute }}分{{ countdownData.second }}秒</view>
              </view>
            </template>
          </x-countdown>
        </view>
        <view class="countdown" v-else>
          <view>此团已结束，您还可以立即开团或参与其他拼团</view>
        </view>
        <view v-if="detail.groupEndTime > nowDate" :class="{'img': true,'flex-star': detail.orderGroupList.length > 6}">
          <view v-for="(item,index) in detail.orderGroupList" :key="index">
            <view class="_item" v-if="index < 11">
              <view v-if="item.groupType === 2">
                <view class="_tag">团长</view>
                <view class="_img">
                  <open-data v-if="userInfo.openId === item.openId" type="userAvatarUrl"></open-data>
                  <x-image v-else :src="item.userHeadImg" />
                </view>
              </view>
              <view v-else>
                <view class="_img">
                  <open-data v-if="userInfo.openId === item.openId && item.groupType !== 2" type="userAvatarUrl"></open-data>
                  <x-image v-if="userInfo.openId !== item.openId && item.groupType !== 2" :src="item. userHeadImg" />
                </view>
              </view>
            </view>
            <view class="_item" v-if="index === 11" @click="showGroupVisibile">
              <view>
                <view class="_img">
                  <x-image src="/assets/images/more.png" />
                </view>
              </view>
            </view>
          </view>
          <view class="_item" v-if="detail.orderGroupList.length < 12">
            <view>
              <view class="_tag" style="background: #F5A28F;color: #FFFFFF;">待参团</view>
              <view class="_img">
                <x-image src="/assets/images/noavatar.png" />
              </view>
            </view>
          </view>
        </view>
        <view v-else :class="{'img': true,'flex-star': detail.orderGroupList.length > 6}">
          <view v-for="(item,index) in detail.orderGroupList" :key="index">
            <view class="_item" v-if="index < 11">
              <view v-if="item.groupType === 2">
                <view class="_tag">团长</view>
                <view class="_img">
                  <open-data v-if="userInfo.openId === item.openId" type="userAvatarUrl"></open-data>
                  <x-image v-else :src="item.userHeadImg" />
                </view>
              </view>
              <view v-else>
                <view class="_img">
                  <open-data v-if="userInfo.openId === item.openId && item.groupType !== 2" type="userAvatarUrl"></open-data>
                  <x-image v-if="userInfo.openId !== item.openId && item.groupType !== 2" :src="item.userHeadImg" />
                </view>
              </view>
            </view>
            <view class="_item" v-if="index === 11" @click="showGroupVisibile">
              <view>
                <view class="_img">
                  <x-image src="/assets/images/more.png" />
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="invite-button">
          <x-button v-if="detail.groupEndTime > nowDate" style="background: linear-gradient(202.81deg, #FF653B 12.5%, #FF3C21 100.68%);" round="true" size="large" @click="joinGroup">
            立即参团
          </x-button>
          <x-button v-else style="background: linear-gradient(202.81deg, #FF653B 12.5%, #FF3C21 100.68%);" round="true" size="large" @click="initiateGroup">
            立即开团
          </x-button>
        </view>
      </view>
    </view>
    <!--服务信息-->
    <view class="server">
      <p-server :serveList="serveList"/>
    </view>
    <!-- 拼团 v-if="detail.orderGroupList[0].groupStatus === 2" -->
    <view v-if="recentlyList" style="margin-top: 16rpx">
      <x-carousel :list="recentlyList" :header="carouselHeader" type="group" button-text="去参团" @change="joinGroup" />
    </view>
    <!-- 用户评价 -->
    <view class="apprise">
      <p-apprise v-if="goodsAppriseList" :detail="goodsAppriseList" :appriseRate="appriseRate" />
    </view>
    <!--商品介绍/规格信息-->
    <view class="detail-tab">
      <!--tabs-->
      <view class="tabs">
        <x-tabs :active="currentTab" :list="tab" underline @change="onChangeTab" />
      </view>
      <!-- 商品详情 -->
      <view v-if="currentTab === 'detail'" class="detail">
        <block style="width: 100%" v-for="(item,index) in currentTabImage" :key="index">
          <x-image :src="item" mode="widthFix"/>
        </block>
      </view>
      <!-- 规格信息 -->
      <view v-if="currentTab === 'sku'" class="sku">
        <view class="ul">
          <view class="li" v-for="(item,index) in productInfo.productAttrValues" :key="index">
            <view class="dd">{{ item.attrName }}</view>
            <view class="dt">{{ item.attrValue }}</view>
          </view>
        </view>
      </view>
    </view>
    <!--服务信息弹框-->
    <p-drawer-service v-if="serviceVisible" :visible.sync="serviceVisible" :serveList="serveList"/>
    <!--SKU弹框-->
    <p-drawer-sku
      v-if="skuVisible"
      :visible.sync="skuVisible"
      :detail="productInfo"
      :orderType="orderType"
      :groupNo="detail.orderGroupList[0].groupNo"
      :groupList="groupList"
      :serveList="serveList"
      :allCouponList="couponList"
    />
    <x-fixed v-if="hideFooter" ref="x-fixed-bottom" fixed direction="bottom">
      <view class="invite-button-bottom">
        <x-button v-if="detail.groupEndTime > nowDate" style="background: linear-gradient(202.81deg, #FF653B 12.5%, #FF3C21 100.68%);" round="true" size="large" @click="joinGroup">
          立即参团
        </x-button>
        <x-button v-else style="background: linear-gradient(202.81deg, #FF653B 12.5%, #FF3C21 100.68%);" round="true" size="large" @click="initiateGroup">
          立即开团
        </x-button>
      </view>
    </x-fixed>
    <view v-if="groupVisible" class="groupDrawer">
      <view class="g-container">
        <view class="g-title">
          拼团详情
          <view class="close" @click="closeGroupVisibile">
            <x-icon name="icon-003" size="54" color="#CCCCCC"/>
          </view>
        </view>
        <scroll-view class="_scroll" scroll-y="true">
          <view :class="{'img': true,'flex-star': detail.orderGroupList.length > 6}">
            <view v-for="(item,index) in detail.orderGroupList" :key="index">
              <view class="_item" v-if="index < 11" :style="{marginRight: (index+1)%5 === 0 ? '0' : '10px'}">
                <view v-if="item.groupType === 3">
                  <view class="_tag">团长</view>
                  <view class="_img">
                    <open-data v-if="userInfo.openId === item.openId" type="userAvatarUrl"></open-data>
                    <x-image v-else :src="item.userHeadImg" />
                  </view>
                </view>
                <view v-else>
                  <view class="_img">
                    <open-data v-if="userInfo.openId === item.openId && item.groupType !== 3" type="userAvatarUrl"></open-data>
                    <x-image v-if="userInfo.openId !== item.openId && item.groupType !== 3" :src="item.userHeadImg" />
                  </view>
                </view>
              </view>
            </view>
            <view class="_item" v-if="detail.groupEndTime < nowDate">
              <view>
                <view class="_tag" style="background: #F5A28F;color: #FFFFFF;">待参团</view>
                <view class="_img">
                  <x-image src="/assets/images/noavatar.png" />
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import config from '@/config';
import XButton from '@/components/x-button';
import XIcon from '@/components/x-icon';
import XOrderGoods from '@/components/x-order-goods';
import XImage from '@/components/x-image';
import XCountdown from '@/components/x-countdown';
import XCarousel from '@/components/x-carousel';
import PDrawerSku from '../goods-detail/components/p-drawer-sku';
import PDrawerService from '../goods-detail/components/p-drawer-service';
import PServer from '../goods-detail/components/p-server';
import PApprise from '../goods-detail/components/p-apprise';
import XTabs from '@/components/x-tabs';
import XFixed from '@/components/x-fixed';
import md5 from 'md5';
import XTools from '@/utils/x-tools';

export default {
  name: 'ShareCollage',
  components: {
    XCarousel,
    XFixed,
    XTabs,
    PApprise,
    PServer,
    PDrawerService,
    PDrawerSku,
    XImage,
    XButton,
    XOrderGoods,
    XCountdown,
    XIcon
  },
  props: {},
  data() {
    return {
      userInfo: uni.getStorageSync(config.userInfoName) || {},
      detail: null,
      orderGoods: null,
      serviceVisible: false,
      skuVisible: false,
      groupVisible: false,
      currentTab: 'detail',
      tab: [{
        name: '商品介绍',
        value: 'detail'
      }, {
        name: '规格信息',
        value: 'sku'
      }],
      orderType: null,
      currentTabImage: [],
      goodsAppriseList: null,
      groupList: null,
      productInfo: null,
      hideFooter: false,
      scrollHeight: 0,
      serveList: [], // 服务信息
      appriseRate: '', //  好评率
      couponList: null, // 可领取优惠券列表
      nowDate: new Date(), // 当前时间
      countdownData: null
    };
  },
  computed: {
    // 参团跑马灯列表
    recentlyList() {
      // 状态：1-进行中；2-拼团成功
      if (this.groupList && this.groupList.length > 2 && this.detail && this.detail.orderGroupList[0].groupStatus === 2) {
        return this.groupList.map((item) => {
          return {
            groupNo: item.groupNo,
            avatar: item.userHeadImg,
            name: item.userNickname,
            desc: `只差<span style="color:#DE3A2E">${item.groupBalance || 1}</span>人成团`
          };
        });
      } else {
        return null;
      }
    },
    // 跑马灯头部信息
    carouselHeader() {
      if (this.detail && this.recentlyList) {
        let hashCode = XTools.hashCode(this.detail.productId);
        if (hashCode < 0) {
          hashCode = 0 - hashCode;
        }
        let num = hashCode % 500;
        if (num < 200) {
          num += 200 + this.recentlyList.length;
        }
        return {
          title: `${num}人已拼，可直接参与`,
          pic: '/assets/images/goods-like.png'
        };
      } else {
        return null;
      }
    }
  },
  onLoad(query) {
    this.query = query;
    this.$nextTick(() => {
      this.userInfo = uni.getStorageSync(config.userInfoName);
      if (!this.userInfo?.accountName) {
        console.log('没有授权');
      } else {
        // 需要主动授权
      }
    });
    this.getOrderDetail();
  },
  watch: {},
  // 滚动页面
  onPageScroll(e) {
    if (e.scrollTop > this.scrollHeight) {
      this.hideFooter = true;
    } else {
      this.hideFooter = false;
    }
  },
  // 分享转发
  onShareAppMessage() {
    const path = `/pages/share-collage/index?orderId=${this.query.orderId}`;
    this.$XTrack('onShareAppMessage');
    return {
      path,
      title: '拼团'
    };
  },
  methods: {
    //  获取订单详情
    async getOrderDetail() {
      const params = {
        orderId: this.query.orderId
      };
      console.log(params);
      // const api = 'http://192.168.10.12:3200/mock/170/order/order/app/detail';
      this.$http({
        login: true,
        // url: api,
        url: '/order/order/app/detail',
        method: 'get',
        report: true,
        data: params
      }).then(res => {
        console.log(res);
        if (res.data.productPrice) {
          res.data.productPrice = this.$tools.formatZero(res.data.productPrice);
        }
        if (res.data.freightAmount) {
          res.data.freightAmount = this.$tools.formatZero(res.data.freightAmount);
        }
        if (res.data.couponAmount) {
          res.data.couponAmount = this.$tools.formatZero(res.data.couponAmount);
        }
        if (res.data.totalPay) {
          res.data.totalPay = this.$tools.formatZero(res.data.totalPay);
        }
        if (res.data.productSku) {
          let t_tmp_args = [];
          t_tmp_args = res.data.productSku.replace(/(\[)|(\])/g, '');
          res.data.productSku = t_tmp_args.split(',');
        }
        this.detail = res.data;
        this.orderGoods = {
          productName: res.data.productTitle,
          productSku: res.data.productSku,
          productPrice: res.data.productPrice,
          productImgUrl: res.data.productImgUrl
        };
        this.getData();
      }).catch(err => {
        console.log(err);
      });
    },
    //  获取商品详情数据
    async getData() {
      const params = {
        productId: this.detail.productId
      };
      console.log(params);
      // const api = 'http://192.168.10.12:3200/mock/170/product/app/spu/detail';
      this.$http({
        login: true,
        // url: api,
        url: '/product/app/spu/detail',
        method: 'get',
        report: true,
        data: params
      }).then(res => {
        console.log(res);
        this.productInfo = res.data;

        if (this.productInfo.skuMode !== 3) {
          // 格式化difference，确保唯一
          this.productInfo.productSku?.forEach(item => {
            const difference = [];
            // 动态生成数组分隔，避免与运营录入的字符冲突
            item.separate = md5(+new Date());
            item.skuSpec.forEach((sku) => {
              difference.push([sku.specName, sku.specValue].join('@|@|@'));
            });
            item.difference = difference.join(item.separate);
          });
        } else {
          this.productInfo?.productComboList.forEach(info => {
            // 格式化difference，确保唯一
            info.productSku?.forEach(item => {
              const difference = [];
              // 动态生成数组分隔，避免与运营录入的字符冲突
              item.separate = md5(+new Date());
              item.skuSpec.forEach((sku) => {
                difference.push([sku.specName, sku.specValue].join('@|@|@'));
              });
              item.difference = difference.join(item.separate);
            });
          });
        }

        //  商品介图片
        const detailPicFind = res.data.productResource.find(item => item.resourceType === String('detailPic'));
        if (detailPicFind) {
          const detailPic = JSON.parse(detailPicFind.resourceContent)?.picList;
          console.log(detailPic);
          this.currentTabImage = detailPic;
        }
        // 服务承诺
        const serveList = [];
        const productSafeguard = res.data.productSafeguard ? res.data.productSafeguard : {};
        if (productSafeguard) {
          if (productSafeguard.deliveryTypeText) {
            const deliveryTypeText = JSON.parse(productSafeguard.deliveryTypeText);
            deliveryTypeText.map((item) => {
              serveList.push(item);
            });
          }
          if (productSafeguard.productPromiseText) {
            const productPromiseText = JSON.parse(productSafeguard.productPromiseText);
            productPromiseText.map((item) => {
              serveList.push(item);
            });
          }
          if (productSafeguard.promiseAfterText) {
            const promiseAfterText = JSON.parse(productSafeguard.promiseAfterText);
            promiseAfterText.map((item) => {
              serveList.push(item);
            });
          }
        }
        this.serveList = serveList;

        this.isLoad = true;
        this.getCommentList(); //  获取商品信息后 获取商品用户评价
        this.getGroupList(); //  获取商品可参团信息
        this.getCouponList();
      }).catch(err => {
        console.log(err);
        this.isDeleted = true;
      });
    },
    //  获取商品可参团信息
    async getGroupList() {
      const params = {
        productId: this.detail.productId
      };
      console.log(params);
      // const api = 'http://192.168.10.12:3200/mock/170/order/order/group/list';
      this.$http({
        login: true,
        // url: api,
        url: '/order/order/group/list',
        method: 'get',
        report: true,
        data: params
      }).then(res => {
        console.log(res);
        this.groupList = res.data;
      }).catch(err => {
        console.log(err);
      });
    },
    //  获取用户评价
    async getCommentList() {
      const params = {
        productId: this.detail.productId
      };
      this.$http({
        login: true,
        url: '/product/comment/product/list',
        method: 'get',
        report: true,
        data: params
      }).then(res => {
        console.log(res);
        if (res.data && res.data.length > 0) {
          res.data.forEach((item) => {
            console.log(item);
            if (item.imgUrls) {
              item.imgUrls = item.imgUrls.split(',');
            }
            if (item.videoUrl) {
              item.videoUrl = item.videoUrl.split(',');
            }
          });
          this.goodsAppriseList = res.data[0];
          this.getAppriseRate();
          console.log(this.goodsAppriseList);
        } else {
          this.goodsAppriseList = { productId: this.detail.productId };
        }
      }).catch(err => {
        console.log(err);
      });
    },
    //  获取用户评价的好评率
    async getAppriseRate() {
      const params = {
        productId: this.detail.productId
      };
      this.$http({
        login: true,
        url: '/product/comment/praise/rate',
        method: 'get',
        report: true,
        data: params
      }).then(res => {
        this.appriseRate = res.data;
      }).catch(() => {
      });
    },
    //  获取领取优惠券列表
    async getCouponList() {
      const params = {
        productId: this.detail.productId,
        storeId: this.productInfo.storeId
      };
      this.$http({
        login: true,
        url: '/marketing/coupon/app/list',
        method: 'get',
        report: true,
        error: false,
        data: params
      }).then(res => {
        // console.log(res);
        // if (res.data && res.data.length > 0) {
        this.couponList = res.data ? res.data : [];
        // }
      }).catch(err => {
        console.log(err);
      });
    },
    joinGroup() {
      console.log('加入拼团！');
      this.skuVisible = true;
      this.orderType = 3;
    },
    initiateGroup() {
      console.log('立即开团');
      this.skuVisible = true;
      this.orderType = 2;
    },
    onChangeTab(e) {
      console.log(e);
      this.currentTab = this.tab[e].value;
      console.log(this.currentTab);
    },
    showGroupVisibile() {
      this.groupVisible = true;
    },
    closeGroupVisibile() {
      this.groupVisible = false;
    },
    // 倒计时更新
    handleCountdownChange(res) {
      this.countdownData = res;
    }

  }
};
</script>

<style lang="scss" scoped>
.container{
  .header{
    .order-status {
      position: relative;
      min-height: 160px;
      background: $uni-color-primary;
      padding: 36px 24px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      ._title {
        color: #FFFFFF;
        font-size: 38px;
        font-weight: bold;
        ._order-tips {
          margin-left: 8px;
          font-size: 28px;
          font-weight: normal;
        }
      }
      .cutdown{
        display: flex;
        align-items: center;
        margin-top: 12px;
        .group-count{
          color: #FFFFFF;
          font-size: 24px;
          display: block;
          border: 1px solid #FFF;
          border-radius: 100px;
          line-height: 36px;
          overflow: hidden;
          ._text{
            padding: 12px 20px;
          }
          ._title_lf{
            padding: 12px 20px;
            width: 50%;
          }
          ._title_rt{
            padding: 12px 20px;
            width: 50%;
            background: #FFFFFF;
            color: $uni-color-primary;
          }
        }
      }
    }
    ._bg{
      width: 100%;
      height: 180px;
      background: linear-gradient(180deg, #EB441F 0%, rgba(235, 68, 31, 0) 100%);
      z-index: 1;
    }
  }
  .card{
    margin: -180px 24px;
    border-radius: 10px;
    background: #FFFFFF;
    padding: 24px 24px 44px 24px;
    .goods-detail{
      border: 1px solid #EBEDF0;
    }
  }
  .server{
    margin-top: 196px;
  }
  .collage{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-top: 76px;
    .img{
      width: 100%;
      display: flex;
      justify-content: center;
      flex-wrap: wrap;
      padding-left: 28px;
      ._item{
        width: 80px;
        height: 80px;
        border-radius: 100px;
        position: relative;
        //background: #FFECEC;
        margin-right: 24px;
        margin-bottom: 24px;
        ._tag{
          min-width: 88px;
          padding: 0 20px;
          white-space: nowrap;
          background: #EB441F;
          border-radius: 50px;
          font-size: 24px;
          color: #FFFFFF;
          text-align: center;
          position: absolute;
          top: -10px;
          left: 50%;
          transform: translateX(-50%);
        }
        ._img{
          width: 80px;
          height: 80px;
          border-radius: 100px;
          background: #FFECEC;
          overflow: hidden;
        }
      }
    }
    .flex-star{
      justify-content: start!important;
    }
    ._title{
      font-size: 32px;
      color: $uni-color-default;
    }
    .countdown{
      margin-bottom: 40px;
      font-size: 28px;
      color: $uni-color-default;
      text-align: center;
      ._time{
        display:flex;
        align-items: center;
        font-size: 28px;
        ._tips{
          color: $uni-color-default;
        }
        ._clock{
          color: $uni-color-primary;
        }
      }
    }
    .invite-button{
      width: 640px;
      margin-top: 40px;
    }
  }
  // 商品介绍/规格信息
  .detail-tab {
    background: #ffffff; margin-top: 16px;
    .sku{
      .ul{
        .li{
          padding: 24px;
          display: flex;
          font-size: 28px;
          border-bottom: 1px solid $uni-page-bg;
          .dd{
            width: 160px;
            color: $uni-color-info;
          }
          .dt{
            flex: 1;
            color: $uni-color-default;
          }
        }
        .li:last-child{
          border-bottom: none;
        }
      }
    }
  }
  .other-goods{
    ._img{ padding: 24px 170px;}
    .recommend{
      padding: 0 24px;
    }
  }

  .invite-button-bottom{
    width: 702px;
    margin: 12px auto 32px auto;
  }
  .groupDrawer {
    position: fixed;
    width: 100%;
    height: 100%;
    z-index: 1000;
    left: 0;
    top: 0;
    display: block;
    overflow: hidden;
    background-color: rgba(0, 0, 0, .5);

    .g-container {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 540px;
      min-height: 640px;
      background: #FFFFFF;
      border-radius: 10px;
      .g-title{
        color: $uni-color-default;
        font-size: 30px;
        padding: 48px 0 32px;
        text-align: center;
        position: relative;
        .close{
          position: absolute;
          right: -50px;
          top: -50px;
        }
      }
      ._scroll {
        min-height: 120px;
        max-height: 520px;
        .img{
          width: 100%;
          display: flex;
          justify-content: center;
          flex-wrap: wrap;
          padding: 20px 30px;
          ._item{
            width: 80px;
            height: 80px;
            border-radius: 100px;
            position: relative;
            //background: #FFECEC;
            margin-right: 20px;
            margin-bottom: 24px;
            ._tag{
              min-width: 88px;
              padding: 0 20px;
              white-space: nowrap;
              background: #EB441F;
              border-radius: 50px;
              font-size: 24px;
              color: #FFFFFF;
              text-align: center;
              position: absolute;
              top: -10px;
              left: 50%;
              transform: translateX(-50%);
            }
            ._img{
              width: 80px;
              height: 80px;
              border-radius: 100px;
              overflow: hidden;
            }
          }
        }
        .flex-star{
          justify-content: start!important;
        }
      }
    }
  }
}

</style>
